//
//  QDFullView3DTableViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/5/5.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit
import HandyJSON

/// 全景列表的item
private struct QDFullViewItem: HandyJSON {
    /// id
    var id = ""
    /// 标题名称
    var title = ""
    /// 跳转的url
    var url = ""

    mutating func mapping(mapper: HelpingMapper) {
        mapper <<<
            self.title <-- "name"
        mapper <<<
            self.url <-- "module_url"
    }
}


/// 3D 全景图的列表
final class QDFullView3DTableViewController: NWTableViewController {

    /// 数据源
    private var items = [QDFullViewItem]()
    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        headerRefreshEnable = false //禁止下拉刷新
        titleForFooterRefreshWithNoMoreData = "--- 数据加载完成 ---"
    }
    
    // 注册cell
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDTitleTableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        tableView.rowHeight = 63
        navigationItem.title = "线路选择"
        // 请求信息
        self.requestAllListMessage()
    }
}

extension QDFullView3DTableViewController {
    
    ///
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        if let titleCell = cell as? QDTitleTableViewCell {
            let item = items[indexPath.row]
            titleCell.titleLabel.text = item.title
        }
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let item = items[indexPath.row]
        guard !item.url.isEmpty else { return }
        
        // 跳入网页
        pushToShareWebViewController(url: item.url, shareTitle: item.title, title: item.title)
    }
    
}


private extension QDFullView3DTableViewController {
    
    /// 请求列表的所有信息
    func requestAllListMessage(){
        
        QDNetworkingManager.request(url: fullViewUrl, isArray: true, arraySuccess: { (msg, datas) in
            
            //进行解析
            self.items = [QDFullViewItem].deserialize(from: datas) as? [QDFullViewItem] ?? [QDFullViewItem]()
            
            //刷新
            self.tableView.reloadData()
            //
            self.refreshFooter.endRefreshingWithNoMoreData()
            
        }) { (msg, type) in
            self.view.showTextHUD(text: msg)
        }
        
    }
}
